package org.example.coffeeshoporderingsystem.order.service.impl;


import org.example.coffeeshoporderingsystem.common.service.impl.BaseServiceImpl;
import org.example.coffeeshoporderingsystem.member.util.MemberUtil;
import org.example.coffeeshoporderingsystem.order.dao.OrderDAO;
import org.example.coffeeshoporderingsystem.order.dao.OrderDetailDAO;
import org.example.coffeeshoporderingsystem.order.dto.AddProductDTO;
import org.example.coffeeshoporderingsystem.order.entity.Order;
import org.example.coffeeshoporderingsystem.order.entity.OrderDetail;
import org.example.coffeeshoporderingsystem.order.service.OrderService;
import org.example.coffeeshoporderingsystem.staff.entity.Staff;
import org.example.coffeeshoporderingsystem.staff.util.StaffUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

@org.springframework.stereotype.Service
@Transactional
public class OrderServiceImpl extends BaseServiceImpl<Order, OrderDAO> implements OrderService {
    @Autowired
    private OrderDetailDAO orderDetailDAO ;

    private Order currOrder = new Order() ;
    @Override
    public Order findByCurrMember() {
        var member = MemberUtil.getMember() ;
        var store = StaffUtil.getStaff().getStore() ;
        currOrder.setOrderId(member.getMemberId());
        currOrder.setMember(member);
        currOrder.setStore(store);
        currOrder.setTotalAmount(0.0);
//        currOrder.setOrderDetailList(new ArrayList<>());
        return currOrder;
    }

    @Override
    public boolean saveOrUpdateProduct(AddProductDTO productDTO) {
        var orderDetail = new OrderDetail() ;
        orderDetail.setDetailId(productDTO.getProduct().getProductId());
        orderDetail.setProduct(productDTO.getProduct());
        orderDetail.setQuantity(productDTO.getQuantity());
        orderDetail.setSubtotal(productDTO.getProduct().getPrice()*productDTO.getQuantity());
        if(currOrder.getOrderId()==null){
            this.findByCurrMember() ;
        }
        orderDetail.setOrder(currOrder);
        currOrder.getOrderDetailList().add(orderDetail) ;
        return true;
    }

    @Override
    public boolean save(Order order) {
        boolean insertOrder = baseDAO.insert(order) ;
        boolean insertOrderDetail = orderDetailDAO.insertBatch(order.getOrderDetailList());
        this.currOrder = new Order() ;
        return insertOrder&&insertOrderDetail;
    }
}
